package com.hnchances.security;

import cn.hutool.json.JSONUtil;
import com.hnchances.pojo.entity.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

public class UnAuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 设置数据字节符
        response.setCharacterEncoding("UTF-8");
        // 设置响应内容为json
        response.setContentType("application/json");
        // 制作响应数据
        Result result = Result.error("用户未认证或者登陆已过期");
        String jsonStr = JSONUtil.toJsonStr(result);
        response.getWriter().write(jsonStr);
    }
}
